import { useEffect, useState } from 'react';
import {
  CSS2DReactObject,
  CSS2DReactObjectEvents,
} from '../common/components/css-2d-react-object/CSS2DReactObject';
import { createPortal } from 'react-dom';
import { userEvents } from '@app-base/module';

export const CSS2DObjectReactRenderer = () => {
  const [objects, setObjects] = useState<CSS2DReactObject[]>([]);

  const removeObject = (target: CSS2DReactObject) => {
    setObjects((old) => old.filter((o) => o !== target));
  };

  const updateObject = (target: CSS2DReactObject) => {
    setObjects((old) => [...old.filter((o) => o !== target), target]);
  };

  useEffect(() => {
    userEvents
      .on(CSS2DReactObjectEvents.Update, updateObject)
      .on(CSS2DReactObjectEvents.Remove, removeObject);

    return () => {
      userEvents
        .off(CSS2DReactObjectEvents.Update, updateObject)
        .off(CSS2DReactObjectEvents.Remove, removeObject);
    };
  }, []);

  return (
    <>
      {objects.map((o) =>
        createPortal(
          <o.ReactComponent
            key={o.uuid}
            {...o.props}
          />,
          o.element,
          o.uuid,
        ),
      )}
    </>
  );
};
